package com.usefullc.common.util;

import com.usefullc.common.exception.BizException;

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class ZipCompressUtils {


    public static void zip(String zipFileName, String sourceFileName) {

        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
            BufferedOutputStream bos = new BufferedOutputStream(out);
            File sourceFile = new File(sourceFileName);
            compress(out, bos, sourceFile, sourceFile.getName());
            bos.close();
            out.close();

        } catch (Exception e) {
            throw new BizException(e);
        }
    }

    public static void compress(ZipOutputStream out, BufferedOutputStream bos, File sourceFile, String base) throws Exception {
        if (sourceFile.isDirectory()) {
            File[] flist = sourceFile.listFiles();
            if (flist.length == 0)//如果文件夹为空，则只需在目的地zip文件中写入一个目录进入点
            {
                System.out.println(base + "/");
//                out.putNextEntry(new ZipEntry(base + "/"));
                out.putNextEntry(new ZipEntry("/"));
            } else//如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
//                    compress(out, bos, flist[i], base + "/" + flist[i].getName());
                    compress(out, bos, flist[i], "/" + flist[i].getName());
                }
            }
        } else {
            //如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
            out.putNextEntry(new ZipEntry(base));
            FileInputStream fos = new FileInputStream(sourceFile);
            BufferedInputStream bis = new BufferedInputStream(fos);

            int tag;
//            System.out.println(base);
            //将源文件写入到zip文件中
            while ((tag = bis.read()) != -1) {
                bos.write(tag);
            }
            bis.close();
            fos.close();

        }
    }

    public static void main(String[] args) {
        try {
            ZipCompressUtils.zip("/Users/long3/workspace/usefullc-platform/usefullc-crawler/src/main/resources/static/extension.zip", "/Users/long3/workspace/usefullc-platform/usefullc-crawler/src/main/resources/static/extension");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
